<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouse">
              <j-search-select-tag
                type="list"
                v-model="model.warehouse"
                dict="hz_wms_warehouse_info,name,id,wms,status='Y'"
                placeholder="请选择可用仓库"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="分区名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partitionName">
              <a-input
                v-model="model.partitionName"
                placeholder="请输入分区名称（最大20个字符）"
                :maxLength="20"
                :disabled="model.warehouse ? false : true"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="分区代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partitionCode">
              <a-input
                v-model="model.partitionCode"
                placeholder="请输入填写3位纯字母"
                :disabled="model.warehouse ? false : true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="货架排数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rowNum">
              <a-input-number
                v-model="model.rowNum"
                placeholder="请填写该分区货架排数（最大支持50排货架）"
                :max="50"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="货架数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="quantity">
              <a-input-number
                v-model="model.quantity"
                placeholder="请填写每排货架数量数（最大支持30个货架）"
                :max="30"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="货架层数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="layerNum">
              <a-input-number
                v-model="model.layerNum"
                placeholder="请填写每个货架层数（最大支持10层）"
                :max="10"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="货架格数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gridNum">
              <a-input-number
                v-model="model.gridNum"
                placeholder="请填写每层货架格数（最大支持10格）"
                :max="10"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="自动优先级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="autoPriority">
              <div class="row">
                <div>
                  <a-switch checkedChildren="开" unCheckedChildren="关" v-model="model.autoPriority" />
                </div>
                <div>开启后，将根据该分区库位总数智能进行优先级设置，效果为拣货路径为蛇形拣货。</div>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <a-modal
      :visible="progressVisible"
      :closable="false"
      :maskClosable="false"
      :width="500"
      @ok="progressFinish"
      :footer="null"
    >
      <div class="progress">
        <div>{{ percentModel.percent < 100 ? '正在创建' : '创建成功' }}</div>
        <a-progress :percent="percentModel.percent" />
        <div v-if="percentModel.percent < 100">正在创建库位，大约剩余{{ percentModel.countdown }}s</div>
      </div>
      <div style="text-align: right" v-if="percentModel.percent === 100">
        <a-button key="submit" type="primary" @click="progressFinish">确定</a-button>
      </div>
    </a-modal>
  </a-spin>
</template>

<script>
import Vue from 'vue'
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { simpleDebounce } from '@/utils/util'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { EventBus } from './eventBus'
export default {
  name: 'ShelvesLocationForm',
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {
        autoPriority: true,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      progressVisible: false,
      socket: '',
      percentModel: {
        percent: 0, //进度
        countdown: '', //倒计时
      },
      validatorRules: {
        warehouse: [{ required: true, message: '请选择可用仓库' }],
        partitionName: [
          { required: true, message: '请输入分区名称' },
          { validator: (rule, value, callback) => this.partitionValidator(rule, value, callback, 'partitionName') },
        ],
        partitionCode: [
          { required: true, message: '请输入分区代码' },
          { pattern: /^[a-zA-Z]{3}$/, message: '请输入3位纯字母' },
          { validator: (rule, value, callback) => this.partitionValidator(rule, value, callback, 'partitionCode') },
        ],
        rowNum: [
          { required: true, message: '请输入该分区货架排数' },
          { pattern: /^(?:[1-9]|[1-4][0-9]|50)$/, message: '请输入大于0小于等于50的整数' },
        ],
        quantity: [
          { required: true, message: '请输入每排货架数量' },
          { pattern: /^(?:[1-9]|1[0-9]|2[0-9]|30)$/, message: '请输入大于0小于等于30的整数' },
        ],
        layerNum: [
          { required: true, message: '请输入每个货架层数' },
          { pattern: /^(?:[1-9]|10)$/, message: '请输入大于0小于等于10的整数' },
        ],
        gridNum: [
          { required: true, message: '请输入每层货架格数' },
          { pattern: /^(?:[1-9]|10)$/, message: '请输入大于0小于等于10的整数' },
        ],
      },
      url: {
        add: '/wms/shelves/shelvesLocation/add',
        edit: '/wms/shelves/shelvesLocation/edit',
        queryById: '/wms/shelves/shelvesLocation/queryById',
        check: '/wms/shelves/shelvesLocation/check',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  mounted() {
    EventBus.$on('websocket-onopen', this.handleOpen)
    EventBus.$on('websocket-message', this.handleMessage)
  },
  methods: {
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
    },
    //分区名称，分区代码  输入校验
    partitionValidator(rule, value, callback, type) {
      if (!this.model.warehouse) {
        callback('请选择仓库')
      }
      if (!value) {
        callback(`请输入${type === 'partitionName' ? '分区名称' : '分区代码'}`)
      } else {
        let parma = {
          warehouse: this.model.warehouse,
        }
        if (type === 'partitionName') {
          parma.partitionName = value
        } else {
          parma.partitionCode = value
        }
        this.checkHandle(parma).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback(res.message)
          }
        })
      }
    },
    checkHandle(parma) {
      return new Promise((resolve, reject) => {
        getAction(this.url.check, parma).then((res) => {
          resolve(res)
        })
      })
    },
    //创建库位
    submitForm: simpleDebounce(function (value) {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.$emit('loadingBack', true)
          that.handleOpen()
          that.handleMessage()
        }
      })
    }, 500),    

    handleOpen() {
      httpAction(this.url.add, this.model, 'post').then((res) => {
        if (!res.success) {
          this.$message.warning(res.message)
        }
      })
    },
    //webscoke 返回消息
    handleMessage(data) {
      if(data && data.msgTxt){
      this.percentModel = {
        percent: data.msgTxt && data.msgTxt.progress ? Number((Number(data.msgTxt.progress) * 100).toFixed()) : 0,
        countdown: data.msgTxt && data.msgTxt.countdown ? data.msgTxt.countdown : '0',
      }
      this.progressVisible = true
      if (this.percentModel.percent === 100) {
        this.confirmLoading = false
        this.$emit('loadingBack', false)
      }
    }
    },
    // 手动关闭连接
    closeConnection(code = 1000, reason = '用户主动关闭') {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        this.socket.close(code, reason)
      }
    },
    //进度完成   关闭webscoket连接
    progressFinish() {
      this.progressVisible = false
      this.$emit('ok')
      EventBus.$off('websocket-onopen', this.handleOpen)
      EventBus.$off('websocket-message', this.handleMessage)
    },
  },
}
</script>
<style lang="less" scoped>
.row {
  width: 100%;
  display: flex;
  align-items: center;
  div:nth-child(1) {
    width: 55px;
  }
  div:nth-child(2) {
    width: calc(100% - 55px);
    border: 1px solid #1890ff;
    font-size: 12px;
    line-height: 17px;
    padding: 4px;
    border-radius: 4px;
    color: #1890ff;
    background: #d6ebff;
  }
}
.progress {
  div:nth-child(1) {
    font-size: 15px;
  }
  /deep/.ant-progress {
    margin: 20px 0 10px 0;
  }
}
</style>